package com.zyx.nettypro.netty.protobuf.multi;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/23 11:13
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送一个 Person 对象到服务器
        Random random = new Random();

        int seed = random.nextInt(3);

        if (seed == 1) {
            PersonPOJO.PersonInfo student = PersonPOJO.PersonInfo.newBuilder()
                    .setPersonType(PersonPOJO.PersonInfo.PersonType.StudentType)
                    .setStudent(PersonPOJO.Student.newBuilder().setId(1001).setName("托塔天王 晁盖").build())
                    .build();
            ctx.writeAndFlush(student);
        } else {
            PersonPOJO.PersonInfo worker = PersonPOJO.PersonInfo.newBuilder()
                    .setPersonType(PersonPOJO.PersonInfo.PersonType.WorkerType)
                    .setWorker(PersonPOJO.Worker.newBuilder().setAge(40).setName("老李").build())
                    .build();
            ctx.writeAndFlush(worker);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器回复的消息:" + buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器的地址： "+ ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
